package com.zjdiepu.www.biz.file;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.processing.OperationStatus;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import com.zjdiepu.www.base.enums.status.MediaProcessStatus;
import com.zjdiepu.www.base.enums.type.AttachmentLabel;
import com.zjdiepu.www.base.enums.type.AttachmentSort;
import com.zjdiepu.www.base.enums.type.AttachmentType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.FileUtil;
import com.zjdiepu.www.common.util.StringUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.config.QiniuProperty;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.dao.other.OtherMediaFailMapper;
import com.zjdiepu.www.dao.system.BaseBusiUnitMapper;
import com.zjdiepu.www.dao.system.BaseCustomerMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.third.JuheProvinceMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.dao.zx.ZxQueryCreditApplySubMapper;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.model.other.dto.OtherMediaFail;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.third.dto.JuheProvince;
import com.zjdiepu.www.model.third.ext.JuheProvinceExt;
import com.zjdiepu.www.model.third.request.NoticeRequest;
import com.zjdiepu.www.model.third.request.NoticeResult;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.util.CachedEnums;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.util.WordUtil;

/**
 * 项目名称：dpqc-parent-manager-file <br/>
 * 类名称：QiniuFileServiceImpl <br/>
 * 类描述： 文件路径<br/>
 * 创建人：winby <br/>
 * 创建时间：2017年4月26日 下午3:08:26  <br/>
 *
 * @version V1.0   <br/>
 */
@Service
public class QiniuFileServiceImpl implements IQiniuFileService {
	@Resource
	private QiniuProperty qiniuProperty;
	@Resource
	private YwBusinessMapper ywBusinessMapper;
	@Resource
	private BaseCustomerMapper baseCustomerMapper;
	@Resource
	private BaseSalersmanMapper baseSalersmanMapper;
	@Resource
	private BaseBusiUnitMapper baseBusiUnitMapper;
	@Resource
	private JuheProvinceMapper juheProvinceMapper;
	@Resource
	private ZxQueryCreditApplySubMapper zxQueryCreditApplySubMapper;
	@Resource
	private OtherAttachmentsMapper otherAttachmentsMapper;
	@Resource
	private OtherMediaFailMapper otherMediaFailMapper;
	@Resource
	private RedisObjectClient redisObjectClient;
	
	public static final Logger logger = LoggerFactory.getLogger(QiniuFileServiceImpl.class);

    private static final String IMG_TYPE = ".jpg";
    private static final String VIDEO_TYPE = ".mp4";
    private static final String ZIP_TYPE = ".zip";
    private static final Integer URL_TIMEOUT = 3600;
    //临时文件路径
    private static final String tempFilePath = "/var/tmp/";
    
    @Override
    public boolean exists(String fileKey) {
    	if(StringUtils.isBlank(fileKey)) {
    		return false;
    	}
    	try {
    		BucketManager bucketManager = getBucketManager();
    		//只检查三个前缀
			FileListing listFiles = bucketManager.listFiles(qiniuProperty.getNewBucket(), fileKey, "", 1, "");
			if(listFiles.items != null && listFiles.items.length > 0){
				for(FileInfo fileInfo : listFiles.items) {
					if(fileKey.equals(fileInfo.key)) {
						return true;
					}
				}
			}
		} catch (QiniuException e) {
			logger.error("检查文件是否存在异常。fileKey：{}, e : {}。",fileKey, e);
		}
    	return false;
    }
    
    @Override
    public String saveRar(String busiId, String applyId) {
    	if(StringUtils.isBlank(busiId)) {
    		ExceptionHelper.thow("999", "业务ID缺失");
    	}
    	YwBusiness ywBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
    	if(null == ywBusiness) {
    		ExceptionHelper.thow("999", "业务数据缺失");
    	}
    	
    	String salesmanId = ywBusiness.getSalesmanId();
    	if(StringUtils.isBlank(salesmanId)) {
    		ExceptionHelper.thow("999", "业务员ID缺失");
    	}
    	
    	BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salesmanId);
    	if(null == baseSalersman) {
    		ExceptionHelper.thow("999", "业务员数据缺失");
    	}
    	
    	String unitId = baseSalersman.getUnitId();
    	if(StringUtils.isBlank(unitId)) {
    		ExceptionHelper.thow("999", "业务单位ID缺失");
    	}
    	
    	BaseBusiUnit baseBusiUnit = baseBusiUnitMapper.selectByPrimaryKey(unitId);
    	if(null == baseBusiUnit) {
    		ExceptionHelper.thow("999", "业务单位数据缺失");
    	}
    	
    	String provinceId = baseBusiUnit.getProvinceId();
    	if(StringUtils.isBlank(provinceId)) {
    		ExceptionHelper.thow("999", "业务单位省份ID缺失");
    	}
    	JuheProvinceExt juheProvinceExt = new JuheProvinceExt();
    	juheProvinceExt.setRows(1);
    	juheProvinceExt.notDeleted();
    	juheProvinceExt.setProId(provinceId);
    	List<JuheProvince> juheProvinces = juheProvinceMapper.selectByExt(juheProvinceExt);
    	JuheProvince juheProvince = null;
    	if(CollectionUtils.isNotEmpty(juheProvinces)) {
    		juheProvince = juheProvinces.get(0);
    	}
    	if(null == juheProvince) {
    		ExceptionHelper.thow("999", "业务单位省份数据缺失");
    	}
    	
    	OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
    	otherAttachmentsExt.setBaseWhere();
    	otherAttachmentsExt.withOutPage();
    	otherAttachmentsExt.setDataid(busiId);
    	otherAttachmentsExt.setExcludeFileLabels(Arrays.asList(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getCode(), AttachmentLabel.YE_WU_FU_JIAN_DA_BAO.getCode(),
    			
    			AttachmentLabel.XHH_QIAN_SHU_HE_TONG_ZHAO_PIAN.getCode(),
    			AttachmentLabel.XHH_QIAN_SHU_HE_TONG_SHI_PIN.getCode(),
    			AttachmentLabel.GONG_YIN_XYK_FENGQI_FUKUAN.getCode(),
    			AttachmentLabel.ZGYH_XYK_FENGQI_FUKUAN.getCode(),
    			AttachmentLabel.XYK_TOUZHI_FUWU_HETONG.getCode(),
    			AttachmentLabel.ANJIE_GUOQIAODAI_JIEKUAN_HETONG.getCode(),
    			AttachmentLabel.GONGYIN_XYK_SQB.getCode(),
    			AttachmentLabel.ZGYH_XYK_SQB.getCode(),
    			AttachmentLabel.AN_JIE_RIBAOBIAO.getCode(),
    			AttachmentLabel.XHH_ZILIAO_GENGDUO.getCode(),
    			AttachmentLabel.XHH_DA_BAO_RAR_LABEL.getCode()));
    	List<OtherAttachments> otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
    	StringBuilder busiAttachments = new StringBuilder();
    	if(CollectionUtils.isNotEmpty(otherAttachments)) {
    		for(OtherAttachments otherAttachment : otherAttachments) {
    			String ossPath = otherAttachment.getOssPath();
    			String url = null;
    			if(StringUtils.isNotBlank(ossPath)) {
    				url = getURL(ossPath);
    			}
    			String mode = (String)CachedEnums.getValue(otherAttachment.getModeId(), ModeIDType.class);
    			AttachmentSort attachmentSort = CachedEnums.getByCode(otherAttachment.getAttachmentSort(), AttachmentSort.class);
    			String sort = attachmentSort.getValue();
    			String belongTo = attachmentSort.getBelongTo();
    			String customLabelName = otherAttachment.getCustomLabelName();
    			if(StringUtils.isBlank(customLabelName)) {
    				customLabelName = (String)CachedEnums.getValue(otherAttachment.getFileLabel(), AttachmentLabel.class);
    			}
    			if(!checkAttachment(otherAttachment.getId(), ossPath, url, mode, sort, customLabelName)){
    				continue;
    			}
    			String fileUrl = UrlSafeBase64.encodeToString(url);
    			busiAttachments.append("/url/" + fileUrl);
    			
    			String fileSuffix = FileUtil.getFileSuffix(ossPath);
    			String fileAliaName = mode + (StringUtils.isBlank(belongTo) ? "" : "_" + belongTo) + "_" + sort + "_" + customLabelName + StringUtil.PERIOD+ (StringUtils.isBlank(fileSuffix) ? "jpg" : fileSuffix);
				try {
					String fileAlias = UrlSafeBase64.encodeToString(fileAliaName.getBytes("gb2312"));
					busiAttachments.append("/alias/" + fileAlias);
				} catch (UnsupportedEncodingException e) {
					logger.error("fileAliaName：{}包含非 charset : {} 字符",fileAliaName, "gb2312");
					continue;
				}
    		}
    	}
    	if(StringUtils.isBlank(applyId)) {
    		applyId = ywBusiness.getQueryCreditApplyId();
    	}
    	otherAttachmentsExt.setDataid(applyId);
    	List<OtherAttachments> applyAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
    	if(CollectionUtils.isNotEmpty(applyAttachments)) {
			for(OtherAttachments applyAttachment : applyAttachments) {
				String ossPath = applyAttachment.getOssPath();
				String url = null;
				if(StringUtils.isNotBlank(ossPath)) {
					url = getURL(ossPath);
				}
				String mode = (String)CachedEnums.getValue(applyAttachment.getModeId(), ModeIDType.class);
				AttachmentSort attachmentSort = CachedEnums.getByCode(applyAttachment.getAttachmentSort(), AttachmentSort.class);
    			String sort = attachmentSort.getValue();
    			String belongTo = attachmentSort.getBelongTo();
				String customLabelName = applyAttachment.getCustomLabelName();
				if(StringUtils.isBlank(customLabelName)) {
					customLabelName = (String)CachedEnums.getValue(applyAttachment.getFileLabel(), AttachmentLabel.class);
				}
				String id = applyAttachment.getId();
				if(!checkAttachment(id, ossPath, url, mode, sort, customLabelName)){
					continue;
				}
				
				String fileUrl = UrlSafeBase64.encodeToString(url);
				busiAttachments.append("/url/" + fileUrl);
				
				String fileSuffix = FileUtil.getFileSuffix(ossPath);
				String fileAliaName = mode + (StringUtils.isBlank(belongTo) ? "" : "_" + belongTo) + "_" + sort + "_" + customLabelName + StringUtil.PERIOD + (StringUtils.isBlank(fileSuffix) ? "jpg" : fileSuffix);
				try {
					String fileAlias = UrlSafeBase64.encodeToString(fileAliaName.getBytes("gb2312"));
					busiAttachments.append("/alias/" + fileAlias);
				} catch (UnsupportedEncodingException e) {
					logger.error("fileAliaName：{}包含非 charset : {} 字符",fileAliaName, "gb2312");
					continue;
				}
			}
    	}
    	String fops = qiniuProperty.getZipLine();
    	if(busiAttachments.length() == 0) {
    		return null;
    	}
    	 Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
         Configuration cfg = new Configuration(Zone.zone0());
         OperationManager operationManager = new OperationManager(auth, cfg);
    	 
         String fileName = "rar_" + DateUtil.dateTo8Str(new Date()) + "_"  + juheProvince.getProName() + "_" + ywBusiness.getCustomerName() + "_" + ywBusiness.getCustomerNo() + ZIP_TYPE;
    	 String saveImgEntry = qiniuProperty.getNewBucket() + ":" + fileName; //save as jpg
    	 fops += busiAttachments.toString();
    	 fops += "|saveas/" + UrlSafeBase64.encodeToString(saveImgEntry);
        
		try {
			String persistentId = operationManager.pfop(qiniuProperty.getNewBucket(), "1.png", fops, qiniuProperty.getPipeline(), 
					qiniuProperty.getNotifyUrl()+"?busiId="+busiId, true);
			logger.info("任务ID：{}.", persistentId);
			
			//删除老数据
			OtherAttachments deletedOtherAttachments = new OtherAttachments();
			deletedOtherAttachments.setDataid(busiId);
			deletedOtherAttachments.setModeId(ModeIDType.ZLDJ.getCode());
			deletedOtherAttachments.setAttachmentType(AttachmentType.RAR.getCode());
			deletedOtherAttachments.setAttachmentSort(AttachmentSort.YE_WU_FU_JIAN_DA_BAO.getCode());
			deletedOtherAttachments.setFileLabel(AttachmentLabel.YE_WU_FU_JIAN_DA_BAO.getCode());
			otherAttachmentsMapper.deletedRefined(deletedOtherAttachments);
			
			//附件生成，暂时不赋值ossPath filename
			OtherAttachments rarOtherAttachments = new OtherAttachments();
			rarOtherAttachments.initInsertData("系统", "系统生成");
			rarOtherAttachments.setModeId(ModeIDType.ZLDJ.getCode());
			rarOtherAttachments.setAttachmentSort(AttachmentSort.YE_WU_FU_JIAN_DA_BAO.getCode());
			rarOtherAttachments.setAttachmentType(AttachmentType.RAR.getCode());
			rarOtherAttachments.setCustomerId(ywBusiness.getCustomerId());
			rarOtherAttachments.setFileLabel(AttachmentLabel.YE_WU_FU_JIAN_DA_BAO.getCode());
			rarOtherAttachments.setFileShowName(fileName);
			rarOtherAttachments.setCustomLabelName(AttachmentLabel.YE_WU_FU_JIAN_DA_BAO.getValue());
			rarOtherAttachments.setDataid(busiId);
			otherAttachmentsMapper.insert(rarOtherAttachments);
			
			//处理记录
			OtherMediaFail otherMediaFail = new OtherMediaFail();
	    	otherMediaFail.setId(UUIDFactory.getUUID());
	    	otherMediaFail.setIdAttachments(rarOtherAttachments.getId());
	    	otherMediaFail.setPersistentId(persistentId);
	    	otherMediaFail.setKeyFile(fileName);
	    	otherMediaFail.setTypeFile(AttachmentType.RAR.getCode());
	    	otherMediaFail.setNum(0);
	    	otherMediaFail.setTimeCreate(new Date());
	    	otherMediaFail.setDataStatus(MediaProcessStatus.DENG_DAI_CHU_LI.getCode());
	    	otherMediaFailMapper.insert(otherMediaFail);
	    	
			return fileName;
		} catch (QiniuException e) {
			logger.error("文件打包失败, busiId : {}, applyId : {}, exception : {}.",busiId, applyId, e);
			return null;
		}
    }
    
    /**
     * 检查附件是否符合
     * @author xiongxiaotun <br/>
     * @Title: checkAttachment  <br/>
     * @Description: 检查附件是否符合  <br/>
     * @param attachmentId
     * @param ossPath
     * @param url
     * @param mode
     * @param sort
     * @param customLabelName
     * @return
     * @version V1.0  <br/>
     */
    private boolean checkAttachment(String attachmentId, String ossPath, String url, String mode,String sort, String customLabelName){
		if(StringUtils.isBlank(ossPath)) {
			logger.warn("附件路径缺失。otherAttachmentId : {}", attachmentId);
			return false;
		}
		
		if(StringUtils.isBlank(url)) {
			logger.warn("附件路径授权失败。otherAttachmentId : {}", attachmentId);
			return false;
		}
		
		if(StringUtils.isBlank(mode)) {
			logger.warn("所处模块缺失，或不匹配。otherAttachmentId : {}", attachmentId);
			return false;
		}
		
		if(StringUtils.isBlank(sort)) {
			logger.warn("附件分类缺失，或不匹配。otherAttachmentId : {}", attachmentId);
			return false;
		}
		
		if(StringUtils.isBlank(customLabelName)) {
			logger.warn("附件标签缺失，或不匹配。otherAttachmentId : {}", attachmentId);
			return false;
		}
		return true;
    }
    
    @Override
    public OperationStatus queryStatusByPersistentId(String persistentId) {
    	 OperationManager operationManager = getOperationManager();
		try {
			 OperationStatus operationStatus = operationManager.prefop(persistentId);
			return operationStatus;
		} catch (QiniuException e) {
			logger.error("查询任务失败。persistentId:{}, 异常：{}.", persistentId, e);
			return null;
		}
    	
    }
    
    @Override
    public void saveNotice(NoticeRequest noticeRequest,String id) {
    	OtherMediaFail otherMediaFail = new OtherMediaFail();
    	otherMediaFail.setId(id);
    	int code = noticeRequest.getCode();
    	otherMediaFail.setDataStatus(code);
		if(code == MediaProcessStatus.CHENG_GONG.getCode()) {
			List<NoticeResult> items = noticeRequest.getItems();
			if(CollectionUtils.isEmpty(items)) {
				return;
			}
			NoticeResult noticeResult = items.get(0);
			String newFileName = noticeResult.getKey();
			otherMediaFail.setKeyFile(newFileName);
		}
		otherMediaFail.setNum(0);
		otherMediaFailMapper.updateByPrimaryKeySelective(otherMediaFail); //失败次数会自动加1
    	
    	
    	/*OtherAttachments otherAttachments = new OtherAttachments();
		otherAttachments.setFileName(newFileName);
		otherAttachments.setOssPath(newFileName);
		otherAttachments.setId(attachmentId);
		otherAttachments.setDpStatus(MediaProcessStatus.CHENG_GONG.getCode());
		otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
		removeFile(fileName);*/
    }
    
    @Override
    public String uploadZx(boolean isKey, String fileName,String... fileUrlOrKeys) {
    	File file = new File(tempFilePath);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	if(ArrayUtils.isEmpty(fileUrlOrKeys)) {
    		ExceptionHelper.thow("999", "文件路径不存在");
    	}
    	
    	List<String> urls = new ArrayList<String>();
    	if(isKey) { //只是key，还需要获取授权地址
    		int length = fileUrlOrKeys.length;
    		for(int i = 0; i < length; i++) {
    			String fileUrlOrKey = fileUrlOrKeys[i];
    			if(exists(fileUrlOrKey)) {
    				urls.add(getURL(fileUrlOrKey));
    			}
    		}
    	}
    	
    	Map<String, String> token = getToken("doc", null);
    	UploadManager uploadManager = getUploadManager();
    	
		String tempWordPath = tempFilePath + fileName;
		long time1 = System.currentTimeMillis();
		logger.info("create word start...");
		WordUtil.createWord(tempWordPath, isKey ? urls.toArray(new String[urls.size()]) : fileUrlOrKeys); 
		long time2 = System.currentTimeMillis();
		logger.info("create word end. cost:{}ms", time2 - time1);
		try {
			logger.info("upload word start...");
			if(exists(fileName)) {
				BucketManager bucketManager = getBucketManager();
		        try {
					bucketManager.delete(qiniuProperty.getNewBucket(), fileName);
				} catch (QiniuException e) {
					logger.error("删除文件异常。fileName:{}, 异常：{}.", fileName, e);
					return null;
				}
			}
			uploadManager.put(tempWordPath, fileName, token.get("token"));
			long time3 = System.currentTimeMillis();
			logger.info("upload word. cost:{}ms", time3 - time2);
		} catch (QiniuException e) {
			ExceptionHelper.thow("100200", e.getMessage());
		}
		//
		new File(tempWordPath).delete();
    	return fileName;
    }
    
    @Override
    public String encodeMedia(String fileName, String mediaType,
    		String attachmentId) {
    	
    	OtherMediaFail otherMediaFail = new OtherMediaFail();
    	String id = UUIDFactory.getUUID();
    	otherMediaFail.setId(id);
    	otherMediaFail.setKeyFile(fileName);
    	otherMediaFail.setIdAttachments(attachmentId);
    	otherMediaFail.setTypeFile(mediaType);
    	otherMediaFail.setNum(0);
    	otherMediaFail.setTimeCreate(new Date());
    	otherMediaFail.setDataStatus(MediaProcessStatus.DENG_DAI_CHU_LI.getCode());
    	if(AttachmentType.IMAGE.getCode().equals(mediaType)) {
    		String persistentId = imagesLim(id, fileName, attachmentId);
    		otherMediaFail.setPersistentId(persistentId);
    	} else if(AttachmentType.VIDEO.getCode().equals(mediaType)){
    		String persistentId = encodeVideo(id, fileName, attachmentId);
    		otherMediaFail.setPersistentId(persistentId);
    	}
    	//文件不存在等导致任务提交失败，任务ID为空
    	if(StringUtils.isBlank(otherMediaFail.getPersistentId())) {
    		return null;
    	}
    	otherMediaFailMapper.insert(otherMediaFail);
    	return id;
    }
    
    @Override
    public String imagesWater(String fileName, String attachmentId) {
    	 OperationManager operationManager = getOperationManager();
    	 String saveJpgEntry = qiniuProperty.getNewBucket() + ":" + fileName; //save as jpg
         String fops = qiniuProperty.getImgWaterMark() +  "|saveas/" + UrlSafeBase64.encodeToString(saveJpgEntry);
         String result;
		try {
			result = operationManager.pfop(qiniuProperty.getNewBucket(), fileName, fops, 
					qiniuProperty.getPipeline(), qiniuProperty.getNotifyUrl() + "?attachmentId=" + attachmentId , true);
			return result;
		} catch (QiniuException e) {
			logger.error("图片打水印失败, fileName : {}, attachmentId : {}, e : {}.",fileName, attachmentId, e);
			return null;
		}
    }

    @Override
    public String imagesLim(String id, String fileName, String attachmentId) {
    	 OperationManager operationManager = getOperationManager();
//    	 avthumb/mp4&#124;saveas/cWJ1Y2tldDpxa2V5;avthumb/flv&#124;saveas/cWJ1Y2tldDpxa2V5Mg==
    	 String newfileName = fileName.split("\\.")[0];
    	 String saveJpgEntry = qiniuProperty.getNewBucket() + ":" + newfileName + IMG_TYPE; //save as jpg
         String fops = qiniuProperty.getImgLimit() +"|" + qiniuProperty.getImgWaterMark() +  "|saveas/" + UrlSafeBase64.encodeToString(saveJpgEntry);
         String result;
		try {
			result = operationManager.pfop(qiniuProperty.getNewBucket(), fileName, fops, 
					qiniuProperty.getPipeline(), qiniuProperty.getNotifyUrl() + "?attachmentId=" + attachmentId + "&id=" + id, true);
			return result;
		} catch (QiniuException e) {
			logger.error("图片处理任务提交失败.", e);
			logger.debug("图片瘦身失败, fileName : {}, attachmentId : {}",fileName, attachmentId);
			return null;
		}
    }
    
    @Override
    public String encodeVideo(String id, String fileName, String attachmentId){
        OperationManager operationManager = getOperationManager();
        String newfileName = fileName.split("\\.")[0];
        String saveMp4Entry = qiniuProperty.getNewBucket() + ":" + newfileName + VIDEO_TYPE; //save as mp4
        String fops = qiniuProperty.getVideoEncode() + "|saveas/" + UrlSafeBase64.encodeToString(saveMp4Entry);
        try {
	        String result = operationManager.pfop(qiniuProperty.getNewBucket(), fileName, fops, qiniuProperty.getPipeline(), qiniuProperty.getNotifyUrl() + "?attachmentId=" + attachmentId + "&id=" + id, true);
	        return result;
        } catch (QiniuException e) {
			logger.error("视频转码任务提交失败.", e);
			logger.debug("视频转码失败, fileName : {}, attachmentId : {}",fileName, attachmentId);
			return null;
		}
    }

    @Override
    public Response removeFile(String fileName) {
       /* BucketManager bucketManager = getBucketManager();
        try {
			return bucketManager.delete(qiniuProperty.getNewBucket(), fileName);
		} catch (QiniuException e) {
			logger.error("删除文件异常。fileName:{}, 异常：{}.", fileName, e);
			return null;
		}*/
    	return moveFile(fileName);
    }

    @Override
    public Response moveFile(String fileName) {
        try {
        	BucketManager bucketManager = getBucketManager();
			return bucketManager.move(qiniuProperty.getNewBucket(), fileName, qiniuProperty.getOldBucket(), fileName, true);
		} catch (QiniuException e) {
			logger.error("移动文件异常。fileName:{}, 异常：{}.", fileName, e);
			return null;
		}
    }

    @Override
    public Map<String, String> getToken(String fileType, String type) {
        Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
        Map<String, String> map = new HashMap<>();
        map.put("token", auth.uploadToken(qiniuProperty.getNewBucket()));
        if(StringUtils.isNotBlank(type)) { //使用最终的文件名（处理后图片jpg，视屏mp4）
        	if(AttachmentType.IMAGE.getCode().equals(type)){
        		map.put("uuid", UUIDFactory.getUUID() + IMG_TYPE);
        	} else if(AttachmentType.VIDEO.getCode().equals(type)){
        		map.put("uuid", UUIDFactory.getUUID() + VIDEO_TYPE);
        	} else { //如果没有匹配，使用后缀
        		map.put("uuid", UUIDFactory.getUUID() + StringUtil.PERIOD + fileType);
        	}
        } else { //使用后缀
        	map.put("uuid", UUIDFactory.getUUID() + StringUtil.PERIOD + fileType);
        }
        return map;
    }

    @Override
    public String getURL(String key) {
        key = qiniuProperty.getGateway() + key;
        Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
        return auth.privateDownloadUrl(key, URL_TIMEOUT);
    }


    private OperationManager getOperationManager() {
        Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
        Configuration cfg = new Configuration(Zone.zone0());
        return new OperationManager(auth, cfg);
    }

    private BucketManager getBucketManager() {
        Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
        Configuration cfg = new Configuration(Zone.zone0());
        return new BucketManager(auth, cfg);
    }
    
    private UploadManager getUploadManager() {
        Configuration cfg = new Configuration(Zone.zone0());
        return new UploadManager(cfg);
    }
    
    @Override
    public String xxhDataZip(String busiId){
		if(StringUtils.isBlank(busiId)) {
    		ExceptionHelper.thow("999", "业务ID缺失");
    	}
    	YwBusiness ywBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
    	if(null == ywBusiness) {
    		ExceptionHelper.thow("999", "业务数据缺失");
    	}
    	
    	String salesmanId = ywBusiness.getSalesmanId();
    	if(StringUtils.isBlank(salesmanId)) {
    		ExceptionHelper.thow("999", "业务员ID缺失");
    	}
    	
    	BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salesmanId);
    	if(null == baseSalersman) {
    		ExceptionHelper.thow("999", "业务员数据缺失");
    	}
    	
    	String unitId = baseSalersman.getUnitId();
    	if(StringUtils.isBlank(unitId)) {
    		ExceptionHelper.thow("999", "业务单位ID缺失");
    	}
    	
    	BaseBusiUnit baseBusiUnit = baseBusiUnitMapper.selectByPrimaryKey(unitId);
    	if(null == baseBusiUnit) {
    		ExceptionHelper.thow("999", "业务单位数据缺失");
    	}
    	
    	String provinceId = baseBusiUnit.getProvinceId();
    	if(StringUtils.isBlank(provinceId)) {
    		ExceptionHelper.thow("999", "业务单位省份ID缺失");
    	}
    	JuheProvinceExt juheProvinceExt = new JuheProvinceExt();
    	juheProvinceExt.setRows(1);
    	juheProvinceExt.notDeleted();
    	juheProvinceExt.setProId(provinceId);
    	List<JuheProvince> juheProvinces = juheProvinceMapper.selectByExt(juheProvinceExt);
    	JuheProvince juheProvince = null;
    	if(CollectionUtils.isNotEmpty(juheProvinces)) {
    		juheProvince = juheProvinces.get(0);
    	}
    	if(null == juheProvince) {
    		ExceptionHelper.thow("999", "业务单位省份数据缺失");
    	}
		OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
    	otherAttachmentsExt.setBaseWhere();
    	otherAttachmentsExt.withOutPage();
    	otherAttachmentsExt.setDataid(busiId);
    	otherAttachmentsExt.setIncludeFileLabels(Arrays.asList(AttachmentLabel.SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode(), 
    			AttachmentLabel.SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode(),
    			AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode(),
    			AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode(),
    			AttachmentLabel.JIE_HUN_ZHENG.getCode(),
    			AttachmentLabel.DAN_SHEN_JU_JIE_SHU.getCode(),
    			AttachmentLabel.JIA_ZHAO.getCode(),
    			AttachmentLabel.TI_CHE_QI_CHE_HE_GE.getCode(),
    			AttachmentLabel.GUO_HU_ER_SHOU_CHE_FA_PIAO.getCode(),
    			AttachmentLabel.TI_CHE_ZHAO.getCode(),
    			AttachmentLabel.XHH_QIAN_SHU_HE_TONG_ZHAO_PIAN.getCode(),
    			AttachmentLabel.XHH_QIAN_SHU_HE_TONG_SHI_PIN.getCode(),
    			AttachmentLabel.GONG_YIN_XYK_FENGQI_FUKUAN.getCode(),
    			AttachmentLabel.ZGYH_XYK_FENGQI_FUKUAN.getCode(),
    			AttachmentLabel.XYK_TOUZHI_FUWU_HETONG.getCode(),
    			AttachmentLabel.ANJIE_GUOQIAODAI_JIEKUAN_HETONG.getCode(),
    			AttachmentLabel.GONGYIN_XYK_SQB.getCode(),
    			AttachmentLabel.ZGYH_XYK_SQB.getCode(),
    			AttachmentLabel.AN_JIE_RIBAOBIAO.getCode(),
    			AttachmentLabel.XHH_ZILIAO_GENGDUO.getCode(),
    			AttachmentLabel.TI_CHE_QI_CHE_FA_PIAO.getCode()));
    	List<OtherAttachments> otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
    	if(otherAttachments==null || otherAttachments.size()==0){
    		return "找不到附件！";
    	}
    	StringBuilder busiAttachments = new StringBuilder();
    	if(CollectionUtils.isNotEmpty(otherAttachments)) {
    		for(OtherAttachments otherAttachment : otherAttachments) {
    			String ossPath = otherAttachment.getOssPath();
    			String url = null;
    			if(StringUtils.isNotBlank(ossPath)) {
    				url = getURL(ossPath);
    			}
    			String mode = (String)CachedEnums.getValue(otherAttachment.getModeId(), ModeIDType.class);
    			AttachmentSort attachmentSort = CachedEnums.getByCode(otherAttachment.getAttachmentSort(), AttachmentSort.class);
    			String sort = attachmentSort.getValue();
    			String belongTo = attachmentSort.getBelongTo();
    			String customLabelName = otherAttachment.getCustomLabelName();
    			if(StringUtils.isBlank(customLabelName)) {
    				customLabelName = (String)CachedEnums.getValue(otherAttachment.getFileLabel(), AttachmentLabel.class);
    			}
    			if(!checkAttachment(otherAttachment.getId(), ossPath, url, mode, sort, customLabelName)){
    				continue;
    			}
    			String fileUrl = UrlSafeBase64.encodeToString(url);
    			busiAttachments.append("/url/" + fileUrl);
    			
    			String fileSuffix = FileUtil.getFileSuffix(ossPath);
    			String fileAliaName = mode + (StringUtils.isBlank(belongTo) ? "" : "_" + belongTo) + "_" + sort + "_" + customLabelName + StringUtil.PERIOD+ (StringUtils.isBlank(fileSuffix) ? "jpg" : fileSuffix);
				try {
					String fileAlias = UrlSafeBase64.encodeToString(fileAliaName.getBytes("gb2312"));
					busiAttachments.append("/alias/" + fileAlias);
				} catch (UnsupportedEncodingException e) {
					logger.error("fileAliaName：{}包含非 charset : {} 字符",fileAliaName, "gb2312");
					continue;
				}
    		}
    	}
    	
    	String applyId = ywBusiness.getQueryCreditApplyId();
    	if(StringUtils.isNotBlank(applyId)){
    		otherAttachmentsExt.setDataid(applyId);
    		List<OtherAttachments> applyAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
    		if(CollectionUtils.isNotEmpty(applyAttachments)) {
    			for(OtherAttachments applyAttachment : applyAttachments) {
    				String ossPath = applyAttachment.getOssPath();
    				String url = null;
    				if(StringUtils.isNotBlank(ossPath)) {
    					url = getURL(ossPath);
    				}
    				String mode = (String)CachedEnums.getValue(applyAttachment.getModeId(), ModeIDType.class);
    				AttachmentSort attachmentSort = CachedEnums.getByCode(applyAttachment.getAttachmentSort(), AttachmentSort.class);
    				String sort = attachmentSort.getValue();
    				String belongTo = attachmentSort.getBelongTo();
    				String customLabelName = applyAttachment.getCustomLabelName();
    				if(StringUtils.isBlank(customLabelName)) {
    					customLabelName = (String)CachedEnums.getValue(applyAttachment.getFileLabel(), AttachmentLabel.class);
    				}
    				String id = applyAttachment.getId();
    				if(!checkAttachment(id, ossPath, url, mode, sort, customLabelName)){
    					continue;
    				}
    				
    				String fileUrl = UrlSafeBase64.encodeToString(url);
    				busiAttachments.append("/url/" + fileUrl);
    				
    				String fileSuffix = FileUtil.getFileSuffix(ossPath);
    				String fileAliaName = mode + (StringUtils.isBlank(belongTo) ? "" : "_" + belongTo) + "_" + sort + "_" + customLabelName + StringUtil.PERIOD + (StringUtils.isBlank(fileSuffix) ? "jpg" : fileSuffix);
    				try {
    					String fileAlias = UrlSafeBase64.encodeToString(fileAliaName.getBytes("gb2312"));
    					busiAttachments.append("/alias/" + fileAlias);
    				} catch (UnsupportedEncodingException e) {
    					logger.error("fileAliaName：{}包含非 charset : {} 字符",fileAliaName, "gb2312");
    					continue;
    				}
    			}
    		}
    	}
    	
    	String fops = qiniuProperty.getZipLine();
    	if(busiAttachments.length() == 0) {
    		return null;
    	}
    	 Auth auth = Auth.create(qiniuProperty.getAccessKey(), qiniuProperty.getSecretKey());
         Configuration cfg = new Configuration(Zone.zone0());
         OperationManager operationManager = new OperationManager(auth, cfg);
    	 
         String fileName = "鑫合汇_" + DateUtil.dateTo8Str(new Date()) + "_"  + juheProvince.getProName() + "_" + ywBusiness.getCustomerName() + "_" + ywBusiness.getCustomerNo() + ZIP_TYPE;
    	 String saveImgEntry = qiniuProperty.getNewBucket() + ":" + fileName; //save as jpg
    	 fops += busiAttachments.toString();
    	 fops += "|saveas/" + UrlSafeBase64.encodeToString(saveImgEntry);
        
		try {
			String persistentId = operationManager.pfop(qiniuProperty.getNewBucket(), "1.png", fops, 
					qiniuProperty.getPipeline(), qiniuProperty.getNotifyUrl()+"?busiId="+busiId, true);
			logger.info("任务ID：{}.", persistentId);
			
			//删除老数据
			OtherAttachments deletedOtherAttachments = new OtherAttachments();
			deletedOtherAttachments.setDataid(busiId);
			deletedOtherAttachments.setModeId(ModeIDType.XHHZLDB.getCode());
			deletedOtherAttachments.setAttachmentType(AttachmentType.RAR.getCode());
			deletedOtherAttachments.setAttachmentSort(AttachmentSort.XHH_FU_JIAN_DA_BAO.getCode());
			deletedOtherAttachments.setFileLabel(AttachmentLabel.XHH_DA_BAO_RAR_LABEL.getCode());
			otherAttachmentsMapper.deletedRefined(deletedOtherAttachments);
			
			//附件生成，暂时不赋值ossPath filename
			OtherAttachments rarOtherAttachments = new OtherAttachments();
			rarOtherAttachments.initInsertData("系统", "系统生成");
			rarOtherAttachments.setModeId(ModeIDType.XHHZLDB.getCode());
			rarOtherAttachments.setAttachmentSort(AttachmentSort.XHH_FU_JIAN_DA_BAO.getCode());
			rarOtherAttachments.setAttachmentType(AttachmentType.RAR.getCode());
			rarOtherAttachments.setCustomerId(ywBusiness.getCustomerId());
			rarOtherAttachments.setFileLabel(AttachmentLabel.XHH_DA_BAO_RAR_LABEL.getCode());
			rarOtherAttachments.setFileShowName(fileName);
			rarOtherAttachments.setCustomLabelName(AttachmentLabel.XHH_DA_BAO_RAR_LABEL.getValue());
			rarOtherAttachments.setDataid(busiId);
			otherAttachmentsMapper.insert(rarOtherAttachments);
			
			//处理记录
			OtherMediaFail otherMediaFail = new OtherMediaFail();
	    	otherMediaFail.setId(UUIDFactory.getUUID());
	    	otherMediaFail.setIdAttachments(rarOtherAttachments.getId());
	    	otherMediaFail.setPersistentId(persistentId);
	    	otherMediaFail.setKeyFile(fileName);
	    	otherMediaFail.setTypeFile(AttachmentType.RAR.getCode());
	    	otherMediaFail.setNum(0);
	    	otherMediaFail.setTimeCreate(new Date());
	    	
	    	otherMediaFail.setDataStatus(MediaProcessStatus.DENG_DAI_CHU_LI.getCode());
	    	otherMediaFailMapper.insert(otherMediaFail);
	    	
			return fileName;
		} catch (QiniuException e) {
			logger.error("文件打包失败, busiId : {}, exception : {}.",busiId, e);
			return null;
		}
	}
}
